#ifndef DOWNLOAD_H
#define DOWNLOAD_H

#include <QObject>
#include <QDebug>
#include <QMessageBox>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QThread>

#include "filedata_t.h"
#include "configfile.h"

class Download : public QObject
{
    Q_OBJECT

public:
    enum Status {
        NO_ERROR,
        /* customer error */
        INVALID_NAME,
        INVALID_PHPSESSID,
        INVALID_FILE_DATA_LIST,
        INVALID_DIR,
        FILE_IS_FOLDER,

        /* network error */
        RESPONSE_ERROR,

        UNDEFINED_ERROR = -1,
    };
    static inline QString errorString(Status code) {
        switch (code) {
        case NO_ERROR               : return "Succeed";
        case INVALID_NAME           : return "Invalid user name";
        case INVALID_PHPSESSID      : return "Invalid PHPSESSID";
        case INVALID_FILE_DATA_LIST : return "Invalid file data list";
        case INVALID_DIR            : return "Invalid download directory";
        case FILE_IS_FOLDER         : return "Download file is folder";
        case UNDEFINED_ERROR        : return "Undefined error";
        default                     : return "The mistake of the mistake";
        }
    }

public: /* func */
    explicit Download(QObject *parent = nullptr);
    explicit Download(QList<file_t> &fileDataList,
                      QString currentBaseDir,
                      QString downloadDir,
                      QObject *parent = nullptr);
    explicit Download(file_t &fileData,
                      QString currentBaseDir,
                      QString downloadDir,
                      QObject *parent = nullptr);
    ~Download();
    void reset();
    void set(QList<file_t> &fileDataList,
             QString currentBaseDir,
             QString downloadDir);
    void set(file_t &fileData,
             QString currentBaseDir,
             QString downloadDir);
    void setDownloadTimeout(int seconds);
    Status startDownload();
    bool isDownloading();
    Status stopDownload();

signals:
    void finished(int code, QString errorString);
private slots:
    void downloadResponse(QNetworkReply *reply);

private: /* var */
    ConfigFile *            settings;
    bool                    downloading;
    QString                 downloadDir;
    QString                 currentBaseDir;
    QList<file_t>           fileDataList;
    QNetworkAccessManager   *netManager;
    QNetworkRequest         *baseRequest;
    QString                 name;
    QString                 phpSessionID;
    int                     downloadFinishedCount;
    int                     downloadFileListSize;

private: /* func */
    Status init();
};

#endif // DOWNLOAD_H
